<template>
    <div>
        <hr>
        <el-tag v-for="(item, index) in hList.slice(2)" :key="`tag-${index}`" round effect="dark"
            :type="item.value ? 'success' : 'info'">
            {{ item.label }}
        </el-tag>
        <hr>
        <motor :motor-info="hList[1]" />
        <hr>
        <el-button v-for="(item, index) in sbList" :key="index" @click="handleClick(item)">{{ item.label }}</el-button>
        <hr>
        <div style="display: flex;">
            <my-chart :options="chartOptions_1" />
            <my-chart :options="chartOptions_2" />
        </div>

    </div>
</template>
<script setup>
import { onBeforeUnmount, onMounted, ref, reactive } from 'vue';
import motor from "../components/motorView.vue"
import myChart from '../components/myChart.vue';

const ws = ref(null);

// 数据列表
const hList = reactive([
    { label: "仪表pos", address: "ID258", type: "Int32", value: 0 },
    { label: "仪表speed", address: "MD258", type: "Int32", value: 0 },
    { label: "H1", address: "Q0.0", type: "Boolean", value: 0 },
    { label: "H2", type: "Boolean", address: "Q0.1", value: 0 },
    { label: "H3", type: "Boolean", address: "Q0.2", value: 0 },
    { label: "H4", type: "Boolean", address: "Q0.3", value: 0 },
    { label: "H5", type: "Boolean", address: "Q0.4", value: 0 },
    { label: "H6", type: "Boolean", address: "Q0.5", value: 0 },
    { label: "位置1到位信号", type: "Boolean", address: "I263.1", value: 0 },
    { label: "位置2到位信号", type: "Boolean", address: "I263.2", value: 0 },
    { label: "位置3到位信号", type: "Boolean", address: "I263.3", value: 0 },
    { label: "位置4到位信号", type: "Boolean", address: "I263.4", value: 0 }
]);

// 按钮列表
const sbList = reactive([
    { label: "SB1停止", type: "Boolean", address: "I0.0", value: "false" },
    { label: "SB2开始", type: "Boolean", address: "I0.1", value: "false" },
    { label: "SB3手自动切换", type: "Boolean", address: "I0.2", value: "false" },
    { label: "SB4正转", type: "Boolean", address: "I0.3", value: "false" },
    { label: "SB5反转", type: "Boolean", address: "I0.4", value: "false" },
    { label: "SQ1", type: "Boolean", address: "I1.0", value: "false" },
    { label: "SQ2", type: "Boolean", address: "I1.1", value: "false" },
    { label: "SQ3", type: "Boolean", address: "I1.2", value: "false" },
    { label: "SQ4", type: "Boolean", address: "I1.3", value: "false" },
    { label: "SQ5_L_LIMIT", type: "Boolean", address: "I1.4", value: "false" },
    { label: "SQ6_R_LIMIT", type: "Boolean", address: "I1.5", value: "false" },
    { label: "急停", type: "Boolean", address: "M1000.0", value: 0 },
    { label: "钝化", type: "Boolean", address: "M1000.3", value: 0 }
]);

// 图表配置
const chartOptions_1 = reactive({
    title: { text: "电机速度" },
    tooltip: { trigger: "axis" },
    xAxis: { data: [] },
    yAxis: {},
    series: { type: "line", data: [] }
});

const chartOptions_2 = reactive({
    title: { text: "电机位置" },
    tooltip: { trigger: "axis" },
    xAxis: { data: [] },
    yAxis: {},
    series: { type: "line", data: [] }
});

onMounted(() => {
    initWebSocket();
})
onBeforeUnmount(() => {
    if (ws.value) {
        ws.value.close()
    }
})

// 初始化WebSocket
const initWebSocket = () => {
    ws.value = new WebSocket("ws://localhost:8080/ws");

    ws.value.onopen = () => {
        console.log("WebSocket连接已建立");
        // 连接建立后发送初始状态请求
        ws.value.send(JSON.stringify({ flag: "status", data: hList }));
    };

    ws.value.onerror = (error) => {
        console.error("WebSocket错误:", error);
    };

    ws.value.onclose = () => {
        console.log("WebSocket连接已关闭");
    };

    ws.value.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data);

            // 更新hList数据
            data.forEach((item, index) => {
                if (hList[index]) {
                    hList[index].value = item.value;
                }
            });

            // 查找特定数据项更新图表
            const posItem = data.find(item => item.label === "仪表pos");
            const speedItem = data.find(item => item.label === "仪表speed");

            if (posItem) {
                updateChart(chartOptions_2, posItem.value);
            }
            if (speedItem){
                updateChart(chartOptions_1, speedItem.value);
            }

        } catch (error) {
            console.error("解析WebSocket消息失败:", error);
        }
    };
};

// 更新图表数据
const updateChart = (chartOptions, value) => {
    const now = new Date();
    const timeLabel = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;

    // 限制数据长度，避免内存无限增长
    if (chartOptions.xAxis.data.length > 50) {
        chartOptions.xAxis.data.shift();
        chartOptions.series.data.shift();
    }

    chartOptions.xAxis.data.push(timeLabel);
    chartOptions.series.data.push(value);

    // 触发响应式更新
    chartOptions.xAxis.data = [...chartOptions.xAxis.data];
    chartOptions.series.data = [...chartOptions.series.data];
};

// 按钮点击处理
const handleClick = (data) => {
    if (!ws.value || ws.value.readyState !== WebSocket.OPEN) {
        console.warn("WebSocket未连接");
        return;
    }
    // 特殊按钮处理
    switch (data.label) {
        case "SQ1":
            motorInfo.value = 500;
            break;
        case "SQ2":
            motorInfo.value = 1000;
            break;
        case "SQ3":
            motorInfo.value = 1500;
            break;
        case "SQ4":
            motorInfo.value = 2000;
            break;
    }

    // 发送按钮置位
    ws.value.send(JSON.stringify({
        flag: "button",
        data: {
            ...data,
            value: "true"
        }
    }));

    setTimeout(() => {
        // 发送按钮复位
        ws.value.send(JSON.stringify({
            flag: "button",
            data: {
                ...data,
                value: "false"
            }
        }));
    }, 3000);


};
</script>
<style lang='less' scoped></style>